package com.linwen.javase.juc;

/**
 * @ClassName _04WaitNotify
 * @Description
 * @Author lin
 * @Date 2022/4/19 下午11:10
 * @Version V1.0
 *
 * .wait()方法必须要使用在while中，这样保证每次唤醒线程都需要重新进行条件判断；
 * 如果使用if会出现虚假唤醒情况，因为wait的特点是在哪里睡着，在哪里醒来，如果使用if进行判断，那么第二次线程被唤醒后，将跳过if判断
 * 直接往下执行。
 * 解决方法为  总是将判断逻辑放在循环中  while
 */
public class _04SyncWaitNotifyThread {
    public static void main(String[] args) {
        WaitNotify waitNotify = new WaitNotify();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    for (int i = 0; i < 10; i++) {
                        waitNotify.incr();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"AAA").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    for (int i = 0; i < 10; i++) {
                        waitNotify.decr();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"BBB").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    for (int i = 0; i < 10; i++) {
                        waitNotify.incr();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"CCC").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    for (int i = 0; i < 10; i++) {
                        waitNotify.decr();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"DDD").start();
    }
}
class WaitNotify{
    private int num = 0;
    public synchronized void incr() throws InterruptedException {
        while (num!=0){
            this.wait();
        }
        System.out.println(Thread.currentThread().getName()+" "+num++);
        notifyAll();
    }
    public synchronized void decr() throws InterruptedException {
        while (num==0){
            this.wait();
        }
        System.out.println(Thread.currentThread().getName()+" "+num--);
        notifyAll();
    }
}
